package com.echovin.esb.gateway.route.database;

import com.echovin.esb.gateway.service.GatewayRouteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.context.ApplicationEventPublisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * database路由数据源
 *
 */
@Slf4j
public class DatabaseRouteDefinitionRepository implements RouteDefinitionRepository {

    private ApplicationEventPublisher publisher;
    @Autowired
    GatewayRouteService gatewayRouteService;

    public DatabaseRouteDefinitionRepository(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    @Override
    public Flux<RouteDefinition> getRouteDefinitions() {
        // 数据库中读取路由信息
        List<RouteDefinition> routeDefinitions = gatewayRouteService.getRoutes();
        log.info("数据库加载路由配置{}", routeDefinitions);
        return Flux.fromIterable(routeDefinitions);
    }

    @Override
    public Mono<Void> save(Mono<RouteDefinition> route) {
        return null;
    }

    @Override
    public Mono<Void> delete(Mono<String> routeId) {
        return null;
    }

    /**
     * 刷新事件
     */
    public void refresh() {
        publisher.publishEvent(new RefreshRoutesEvent(this));
    }
}
